package ystp.controller;


import jxl.Workbook;
import jxl.format.UnderlineStyle;
import jxl.write.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import ystp.model.*;
import ystp.service.*;
import ystp.support.JsonResult;
import ystp.support.StringHandle;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("yuecaikangjunyaowujieguo")
public class YuecaikangjunyaowujieguoController {

    @Resource
    YuecaikangjunyaowujieguoService ddService;

    @Resource
    YuecaikangjunyaowuService ddYuecaikangjunyaowuService;

    @Resource
    YsuserService ddYsuserService;

    @Resource
    YsrenyuanfenpeiService ddYsrenyuanfenpeiService;

    @Resource
    YsxiangmuService ddYsxiangmuService;

    public Logger log = LoggerFactory.getLogger(YuecaikangjunyaowujieguoController.class);


    @RequestMapping("getYuecaikangjunResultCount")
    public JsonResult<?> getYuecaikangjunResultCount(@RequestParam("xiangmuid") String ppxiangmuId,
                                             @RequestParam("userid") String ppuserId){
        try {
            Integer mmTongyishu=ddService.getYuecaikangjunResultCount(ppxiangmuId,ppuserId,"1");
            Integer mmButongyishu=ddService.getYuecaikangjunResultCount(ppxiangmuId,ppuserId,"0");
            Integer mmTotal=ddYuecaikangjunyaowuService.getYuecaiCount(ppxiangmuId);
            Map<String, Object> mmMap = new HashMap<String, Object>();
            mmMap.put("tongyiShu", mmTongyishu);
            mmMap.put("butongyiShu", mmButongyishu);
            mmMap.put("total", mmTotal);
            return JsonResult.getSuccessResult(mmMap);
        }catch (Exception e) {
            e.printStackTrace();
            log.error("yuecaikangjunyaowujieguo/getYuecaikangjunResultCount:error",e);
            return JsonResult.getErrorResult("yuecaikangjunyaowujieguo/getYuecaikangjunResultCount:error " + e.getMessage());
        }
    }

    @RequestMapping("toupiao")
    public JsonResult<?> toupiao(@RequestParam("id") String ppdetailId,
                                 @RequestParam("userid") String ppuserId,
                                 @RequestParam("result") String ppresult){
        try {
            Yuecaikangjunyaowujieguo mmYuecaikangjunyaowujieguo = new Yuecaikangjunyaowujieguo();
            Yuecaikangjunyaowu mmYuecaikangjunyaowu = ddYuecaikangjunyaowuService.findOne(ppdetailId);

            Ysxiangmu mmYsxiangmu=ddYsxiangmuService.findOne(mmYuecaikangjunyaowu.getXiangmuid());
            if(mmYsxiangmu.getIsactived()!=1){
                return JsonResult.getErrorResult("表决失败，投票尚未启动");
            }

            if("1".equals(ppresult)) {
                int mmTongyiCount = ddService.getYuecaikangjunResultCount(mmYuecaikangjunyaowu.getXiangmuid(),ppuserId,"1");
                if (mmTongyiCount>=5){
                    return JsonResult.getErrorResult("表决失败，超过限制数");
                }
            }
            if (ddService.checkExistByUserId(ppdetailId,ppuserId)!=null){
                String mmId = ddService.checkExistByUserId(ppdetailId,ppuserId).getId();
                mmYuecaikangjunyaowujieguo = ddService.findOne(mmId);
                mmYuecaikangjunyaowujieguo.setUserid(ppuserId);
                mmYuecaikangjunyaowujieguo.setResult(ppresult);
                return ddService.modify(mmYuecaikangjunyaowujieguo) == true ? JsonResult.getSuccessResult("表决成功")
                        : JsonResult.getErrorResult("表决失败");
            }else{
                mmYuecaikangjunyaowujieguo.setId(UUID.randomUUID().toString());
                mmYuecaikangjunyaowujieguo.setDetailid(ppdetailId);
                mmYuecaikangjunyaowujieguo.setCreatetime(new Date());
                mmYuecaikangjunyaowujieguo.setUserid(ppuserId);
                mmYuecaikangjunyaowujieguo.setResult(ppresult);
                return ddService.add(mmYuecaikangjunyaowujieguo) == true ? JsonResult.getSuccessResult("表决成功")
                        : JsonResult.getErrorResult("表决失败");
            }

        }catch (Exception e) {
            e.printStackTrace();
            log.error("yuecaikangjunyaowujieguo/toupiao:error",e);
            return JsonResult.getErrorResult("yuecaikangjunyaowujieguo/toupiao:error " + e.getMessage());
        }
    }

    @RequestMapping("submit")
    public JsonResult<?> submit(
            @RequestParam("xiangmuid") String ppxiangmuId,
            @RequestParam("userid") String ppuserId,
            HttpServletRequest request) {
        try {
            List<Ysrenyuanfenpei> list = ddYsrenyuanfenpeiService.findbyUserIDandXiangmuId(ppuserId, ppxiangmuId);
            if (list.size() < 1) {
                return JsonResult.getErrorResult("提交失败，人员-项目分配信息不存在");
            }

            List<Yuecaikangjunyaowu> mmYuecaiList = ddYuecaikangjunyaowuService.findByChuangxin("生物创新药");
            for (int i = 0; i < mmYuecaiList.size(); i++) {
                String mmId = mmYuecaiList.get(i).getId();
                if (ddService.checkExistByUserId(mmId, ppuserId)==null||ddService.checkExistByUserId(mmId, ppuserId).getResult().equals("0")) {
                    return JsonResult.getErrorResult("提交失败，南京市生物创新药必选。");
                }
            }

            Integer mmTongyishu = ddService.getYuecaikangjunResultCount(ppxiangmuId, ppuserId, "1");
            if (mmTongyishu > (4 + mmYuecaiList.size())) {
                return JsonResult.getErrorResult("提交失败，除南京市生物创新药外最多选择4项。");
            }

            Ysrenyuanfenpei mmRenyuanfenpei = ddYsrenyuanfenpeiService.findOne(list.get(0).getId());
            mmRenyuanfenpei.setIssubmit(1);
            mmRenyuanfenpei.setUpdatetime(new Date());
            HttpSession session = request.getSession();
            mmRenyuanfenpei.setUpdateby(session.getAttribute("Id").toString());
            return ddYsrenyuanfenpeiService.update(mmRenyuanfenpei) == true ? JsonResult.getSuccessResult("提交成功")
                    : JsonResult.getErrorResult("提交失败");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("yuecaikangjunyaowujieguo/submit:error", e);
            return JsonResult.getErrorResult("yuecaikangjunyaowujieguo/submit:error " + e.getMessage());
        }
    }

    // 导出某个委员的签字表
    @RequestMapping("qianzibiao")
    public void qianzibiao(HttpServletRequest request, HttpServletResponse response,
                           @RequestParam("xiangmuid") String ppxiangmuid,
                           @RequestParam("xiangmuleixing") String ppxiangmuleixing,
                           @RequestParam("userid") String ppuserid) {
        try {
            ddService.daochuqianzibiao(ppxiangmuid, ppuserid, request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("findHuizongbiaolist")
    public JsonResult<?> findHuizongbiaolist(@RequestParam("xiangmuid") String ppxiangmuid){
        try {
            List<Ysrenyuanfenpei> mmUserList=ddYsrenyuanfenpeiService.findUserByXiangmuId(ppxiangmuid);
            Double mm=((double)1/(double)2)*mmUserList.size();
            int mmTongguopiaoshu=(int)Math.ceil(mm);

            List<Map<String,Object>> mmList=ddService.getHuizongbiao(ppxiangmuid);
            for (int i=0; i<mmList.size();i++) {
                String mmDetailId = mmList.get(i).get("id").toString();
                String mmPiaoshu = mmList.get(i).get("piaoshu")==null?"0":mmList.get(i).get("piaoshu").toString();
                String mmPiaoshuText = mmPiaoshu + "/" + String.valueOf(mmUserList.size());
                String mmJieguotext="不通过";
                if(Integer.valueOf(mmPiaoshu)>=mmTongguopiaoshu){
                    mmJieguotext="通过";
                }
                mmList.get(i).put("paiming",i+1);
                mmList.get(i).put("piaoshu",mmPiaoshuText);
                mmList.get(i).put("jieguo",mmJieguotext);
            }

            return JsonResult.getSuccessResult(mmList);

        }catch (Exception e) {
            e.printStackTrace();
            log.error("yuecaikangjunyaowujieguo/findHuizongbiaolist:error",e);
            return JsonResult.getErrorResult("yuecaikangjunyaowujieguo/findHuizongbiaolist:error " + e.getMessage());
        }
    }

    @RequestMapping("huizongbiao")
    public void huizongbiao(HttpServletRequest request, HttpServletResponse response,
                            @RequestParam("xiangmuid") String ppxiangmuid,
                            @RequestParam("xiangmuleixing") String ppxiangmuleixing){
        response.reset();
        response.setContentType("application/x-download;charset=utf-8");
        OutputStream os=null;
        WritableWorkbook wbook=null;

        List<Ysrenyuanfenpei> mmUserList=ddYsrenyuanfenpeiService.findUserByXiangmuId(ppxiangmuid);
        Double mm=((double)1/(double)2)*mmUserList.size();
        int mmTongguopiaoshu=(int)Math.ceil(mm);


        List<Map<String,Object>> mmList=ddService.getHuizongbiao(ppxiangmuid);
        for (int i=0; i<mmList.size();i++) {
            String mmDetailId = mmList.get(i).get("id").toString();
            String mmPiaoshu = mmList.get(i).get("piaoshu")==null?"0":mmList.get(i).get("piaoshu").toString();
            String mmPiaoshuText = mmPiaoshu + "/" + String.valueOf(mmUserList.size());
            String mmJieguotext="不通过";
            if(Integer.valueOf(mmPiaoshu)>=mmTongguopiaoshu){
                mmJieguotext="通过";
            }
            mmList.get(i).put("paiming",i+1);
            mmList.get(i).put("piaoshu",mmPiaoshuText);
            mmList.get(i).put("jieguo",mmJieguotext);
        }

        //mmList = mmList.stream().sorted(Comparator.comparing(map -> (String) map.get("piaoshu"))).collect(Collectors.toList());

        try
        {
            os = new BufferedOutputStream(response.getOutputStream());//得到输出流的语句
            //response.getOutputStream();// 取得输出流
            response.reset();// 清空输出流
            SimpleDateFormat mmDateFormat = new SimpleDateFormat("yyyyMMdd-HHmmss");
            String wenjiantitle = "医保约定采购药品目录抗菌药物汇总表"+ StringHandle.tiemString(); //文件名
            String tmptitle = "医保约定采购药品目录抗菌药物投票表"; // 标题
            response.setHeader("Content-disposition", "attachment; filename="+new String(wenjiantitle.getBytes(),"iso8859-1")+".xls");// 设定输出文件头
            response.setContentType("application/vnd.ms-excel");// 定义输出类型
            wbook = Workbook.createWorkbook(os); // 建立excel文件
            WritableSheet wsheet = wbook.createSheet(tmptitle, 0); // sheet名称
            // 设置excel标题
            WritableFont wfont = new WritableFont(WritableFont.ARIAL, 20,WritableFont.BOLD,false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK); //设置表格样式

            WritableCellFormat wcfFC = new WritableCellFormat(wfont);
            wcfFC.setBorder(jxl.format.Border.ALL,jxl.format.BorderLineStyle.THIN); // 添加边框
            wcfFC.setVerticalAlignment(VerticalAlignment.CENTRE);   //设置居中对齐
            wcfFC.setAlignment(Alignment.CENTRE);

            WritableCellFormat wcfFC3 = new WritableCellFormat(wfont);
            wcfFC3.setVerticalAlignment(VerticalAlignment.CENTRE);   //设置居中对齐
            wcfFC3.setAlignment(Alignment.CENTRE);
            //wcfFC.setBackground(Colour.AQUA);
            Label label=new Label(0, 0, tmptitle, wcfFC3);

            WritableCellFormat cellFormat=new WritableCellFormat();
            cellFormat.setAlignment(jxl.format.Alignment.CENTRE);
            cellFormat.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
            cellFormat.setWrap(true);
            cellFormat.setFont(wfont);
            label.setCellFormat(cellFormat);
            wsheet.addCell(label);
            wsheet.addCell(new Label(0, 0, tmptitle, wcfFC3));
            wsheet.setRowView(0,800); //第一行高度
            wsheet.setColumnView(0,20); //宽度
            wsheet.mergeCells(0, 0, 12, 0);  //合并单元格(第一列的第一行和第十三列的第一行合并)
            wsheet.setColumnView(1,20); //宽度
            wsheet.setColumnView(2,20); //宽度
            wsheet.setColumnView(3,20); //宽度
            wsheet.setColumnView(4,20); //宽度
            wsheet.setColumnView(5,20); //宽度
            wsheet.setColumnView(6,20); //宽度
            wsheet.setColumnView(7,20); //宽度
            wsheet.setColumnView(8,50); //宽度
            wsheet.setColumnView(9,20); //宽度
            wsheet.setColumnView(10,20); //宽度
            wsheet.setColumnView(11,20); //宽度
            // 开始生成主体内容
            wfont = new jxl.write.WritableFont(WritableFont.ARIAL, 12,WritableFont.BOLD,false, UnderlineStyle.NO_UNDERLINE,Colour.BLACK);
            wcfFC = new WritableCellFormat(wfont);
            wcfFC.setBorder(jxl.format.Border.ALL,jxl.format.BorderLineStyle.THIN);
            wcfFC.setVerticalAlignment(VerticalAlignment.CENTRE);   //设置居中对齐
            wcfFC.setAlignment(Alignment.CENTRE);
            wcfFC.setWrap(true);
            // 不需要边框和居中的样式
            WritableCellFormat wcfFC2 = new WritableCellFormat(wfont);
            wcfFC2 = new WritableCellFormat(wfont);
            wcfFC2.setWrap(true);

            wsheet.addCell(new Label(0, 1, "排名",wcfFC));
            wsheet.addCell(new Label(1, 1, "序号",wcfFC));
            wsheet.addCell(new Label(2, 1, "药品名称",wcfFC));
            wsheet.addCell(new Label(3, 1, "医保",wcfFC));
            wsheet.addCell(new Label(4, 1, "院本部药",wcfFC));
            wsheet.addCell(new Label(5, 1, "秦淮药",wcfFC));
            wsheet.addCell(new Label(6, 1, "药品类别",wcfFC));
//            wsheet.addCell(new Label(7, 1, "专科分组",wcfFC));
//            wsheet.addCell(new Label(8, 1, "申请科室",wcfFC));
            wsheet.addCell(new Label(7, 1, "抗菌药物小组会预选意见（得票数/总票数）",wcfFC));
            wsheet.addCell(new Label(8, 1, "国家平台备注信息",wcfFC));
            wsheet.addCell(new Label(9, 1, "规格1",wcfFC));
            wsheet.addCell(new Label(10, 1, "规格2",wcfFC));
            wsheet.addCell(new Label(11, 1, "委员表决票数(同意数/总票数)",wcfFC));
            wsheet.addCell(new Label(12, 1, "表决结果",wcfFC));
            // 表头结束

            wfont = new jxl.write.WritableFont(WritableFont.ARIAL, 12,WritableFont.NO_BOLD,false, UnderlineStyle.NO_UNDERLINE,Colour.BLACK);
            wcfFC = new WritableCellFormat(wfont);
            wcfFC.setBorder(jxl.format.Border.ALL,jxl.format.BorderLineStyle.THIN);
            wcfFC.setVerticalAlignment(VerticalAlignment.CENTRE);   //设置居中对齐
            wcfFC.setAlignment(Alignment.CENTRE);
            wcfFC.setWrap(true);

            int count=mmList.size();
            int mmKaishihang=2;

            for (int i = 0; i < mmList.size(); i++) {
                Map<String,Object> mmMap = mmList.get(i);
                if (mmMap!=null){
                    String mmPaiming = mmMap.get("paiming")==null ? "" :mmMap.get("paiming").toString();
                    String mmXuhao = mmMap.get("ordernumber")==null ? "" :mmMap.get("ordernumber").toString();
                    String mmyaopinmingcheng=mmMap.get("yaopinmingcheng")==null ? "" :mmMap.get("yaopinmingcheng").toString();
                    String mmYibao=mmMap.get("yibao")==null ? "" :mmMap.get("yibao").toString();
                    String mmYuanbenbu=mmMap.get("yuanbenbuyao")==null ? "" :mmMap.get("yuanbenbuyao").toString();
                    String mmQinhuai=mmMap.get("qinhuai")==null ? "" :mmMap.get("qinhuai").toString();
                    String mmNanjingchuangxin=mmMap.get("nanjingchuangxin")==null ? "" :mmMap.get("nanjingchuangxin").toString();
                    String mmZhuankefenzu=mmMap.get("zhuankefenzu")==null ? "" :mmMap.get("zhuankefenzu").toString();
                    String mmShenqingkeshi=mmMap.get("shenqingkeshi")==null ? "" :mmMap.get("shenqingkeshi").toString();
                    String mmBeizhu=mmMap.get("beizhu")==null ? "" :mmMap.get("beizhu").toString();
                    String mmresult=mmMap.get("result")==null ? "" :mmMap.get("result").toString();
                    String mmbiaojueren=mmMap.get("username")==null ? "" :mmMap.get("username").toString();
                    String mmpiaoshu=mmMap.get("piaoshu")==null ? "" :mmMap.get("piaoshu").toString();
                    String mmjieguo=mmMap.get("jieguo")==null ? "" :mmMap.get("jieguo").toString();
                    String mmBeizhu2=mmMap.get("beizhu2")==null ? "" :mmMap.get("beizhu2").toString();
                    String mmBeizhu3=mmMap.get("beizhu3")==null ? "" :mmMap.get("beizhu3").toString();
                    String mmBeizhu4=mmMap.get("beizhu4")==null ? "" :mmMap.get("beizhu4").toString();

                    wsheet.addCell(new Label(0, mmKaishihang,mmPaiming,wcfFC));
                    wsheet.addCell(new Label(1, mmKaishihang,mmXuhao,wcfFC));
                    wsheet.addCell(new Label(2, mmKaishihang,mmyaopinmingcheng,wcfFC));
                    wsheet.addCell(new Label(3, mmKaishihang,mmYibao,wcfFC));
                    wsheet.addCell(new Label(4, mmKaishihang,mmYuanbenbu,wcfFC));
                    wsheet.addCell(new Label(5, mmKaishihang,mmQinhuai,wcfFC));
                    wsheet.addCell(new Label(6, mmKaishihang,mmNanjingchuangxin,wcfFC));
                    wsheet.addCell(new Label(7, mmKaishihang,mmBeizhu4,wcfFC));
                    wsheet.addCell(new Label(8, mmKaishihang,mmBeizhu,wcfFC));
                    wsheet.addCell(new Label(9, mmKaishihang,mmBeizhu2,wcfFC));
                    wsheet.addCell(new Label(10, mmKaishihang,mmBeizhu3,wcfFC));
                    wsheet.addCell(new Label(11, mmKaishihang,mmpiaoshu,wcfFC));

//                    wsheet.addCell(new Label(8, mmKaishihang,mmBeizhu,wcfFC));
//                    wsheet.addCell(new Label(9, mmKaishihang,mmShenqingkeshi,wcfFC));
//                    wsheet.addCell(new Label(9, mmKaishihang,mmBeizhu,wcfFC));
//                    wsheet.addCell(new Label(10, mmKaishihang,mmpiaoshu,wcfFC));
                    if("通过".equals(mmjieguo)){
                        wsheet.addCell(new Label(12, mmKaishihang,mmjieguo,wcfFC));
                    }else {

                        WritableFont wfont1 = new jxl.write.WritableFont(WritableFont.ARIAL, 12, WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.RED);
                        WritableCellFormat wcfFC1 = new WritableCellFormat(wfont1);
                        wcfFC1.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
                        wcfFC1.setVerticalAlignment(VerticalAlignment.CENTRE);   //设置居中对齐
                        wcfFC1.setAlignment(Alignment.CENTRE);
                        wcfFC1.setWrap(true);

                        wsheet.addCell(new Label(12, mmKaishihang,mmjieguo,wcfFC1));
                    }


                    mmKaishihang = mmKaishihang+1;
                }
            }
            wbook.write(); // 写入文件
            wbook.close();
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }finally{
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

}
